package com.kws.tool.service.impl;

import com.aliyun.dyplsapi20170525.Client;
import com.aliyun.dyplsapi20170525.models.*;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.kws.common.security.utils.SecurityUtils;
import com.kws.tool.dto.VirtualDto;
import com.kws.tool.service.VirtualNumberService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author : zhangbenting
 * @date : 2024/10/25 14:53
 * @Version: 1.0
 */
@Service
public class VirtualNumberServiceImpl implements VirtualNumberService {

    @Value("${aliyun.pool-key}")
    private String poolKey;

    @Value("${aliyun.access-key-id}")
    private String accessKeyId;

    @Value("${aliyun.access-key-secret}")
    private String accessKeySecret;


    private Client initClient() throws Exception {
        return new Client(new Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret)
                .setEndpoint("dyplsapi.aliyuncs.com")  // 设置阿里云的 API 端点
        );
    }

    @Override
    public VirtualDto bindVirtualNumber(String phoneA, String phoneB) {
        String expiration = generateExpirationForDays();
        System.out.println("生成的时间数据=======>: " + expiration);
        try {
            Client client = initClient();
            BindAxbRequest request = new BindAxbRequest()
                    .setPoolKey(poolKey)
                    .setPhoneNoA(phoneA)
                    .setPhoneNoB(phoneB)
                    .setExpiration(expiration);

            RuntimeOptions runtime = new RuntimeOptions();
            BindAxbResponse response = client.bindAxbWithOptions(request, runtime);

            if ("OK".equals(response.getBody().getCode())) {
                VirtualDto virtualDto = new VirtualDto();
                virtualDto.setSecretNo(response.getBody().getSecretBindDTO().getSecretNo());
                virtualDto.setSubsId(response.getBody().getSecretBindDTO().getSubsId());
                virtualDto.setExtension(response.getBody().getSecretBindDTO().getExtension());
                return virtualDto;
            } else {
                throw new RuntimeException("绑定失败：" + response.getBody().getMessage());
            }
        } catch (Exception e) {
            throw new RuntimeException("绑定虚拟号码过程中出错：" + e.getMessage(), e);
        }
    }

    private String generateExpirationForDays() {
        // 设置过期时间为7天后
        LocalDateTime now = LocalDateTime.now(ZoneId.of("UTC"));
        LocalDateTime expireDate = now.plusDays(7);

        // 使用简单日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        return formatter.format(expireDate);
    }

    // 解绑虚拟号码
    public boolean unbindVirtualNumber(String subsId) {
        try {
            Client client = initClient();
            UnbindSubscriptionRequest request = new UnbindSubscriptionRequest()
                    .setPoolKey(poolKey)
                    .setSubsId(subsId);
            RuntimeOptions runtime = new RuntimeOptions();
            UnbindSubscriptionResponse response = client.unbindSubscriptionWithOptions(request, runtime);

            if (!"OK".equals(response.getBody().getCode())) {
                throw new RuntimeException("解绑失败：" + response.getBody().getMessage());
            } else {
                return true;
            }
        } catch (Exception e) {
            throw new RuntimeException("解绑虚拟号码过程中出错：" + e.getMessage(), e);
        }
    }

}
